<?php

require_once realpath('..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'bootstrap.php');
$result = array('success' => 'false', 'msg' => 'Error');
header('Content-Type: application/json');
$request = Bike_Service_Locator::getService('Request');
$userManager = Bike_Service_Locator::getService('UserManager');
if($userManager->getCurrentUser() == $userManager->getAnonymous()){
	echo json_encode($result);
	die();
}

$templatesPath = Bike_Service_Locator::getService('Parser_bo')->getTemplatePath();
$request = Bike_Service_Locator::getService('Request');
$result = array();
$os = strtoupper(substr(PHP_OS, 0, 3));
switch(strtolower($request->getRequestVar('type'))){
	case 'list':
		$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($templatesPath));
		while($iterator->valid()){
			$path = $iterator->getSubPathName();
			if(strpos($path, '.') !== 0 && strpos($path, DIRECTORY_SEPARATOR . '.') === false && substr($path, -4) == '.tpl'){
				$result[] = array(
							'path' => ( $os == 'WIN' ? str_replace(DIRECTORY_SEPARATOR, '/', $path) : $path),
							'name' => $iterator->getFileName()
				);
			}
			$iterator->next();
		}
		break;
	case 'tree':
		$node = $request->getRequestVar('node');
		if(empty($node)){
			$node = '';
		}
		$path = realpath($templatesPath . $node);
		if(empty($path) || strpos($path, $templatesPath) !== 0){
			$path = $templatesPath;
		}
		if(is_dir($path)){
			$iterator = new DirectoryIterator( rtrim($path, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR);
			while($iterator->valid()){
				$path = str_replace($templatesPath, DIRECTORY_SEPARATOR, $iterator->getPathname());
				if(strpos($path, '.') !== 0 && strpos($path, DIRECTORY_SEPARATOR . '.') === false && ($iterator->isDir() || ( $iterator->isFile() && substr($path, -4) == '.tpl'))){
					$path = ( $os == 'WIN' ? str_replace(DIRECTORY_SEPARATOR, '/', $path) : $path);
					$result[] = array(
								'href' => $path,
								'text' => $iterator->getFileName(),
								'id' => $path,
								'leaf' => !$iterator->isDir()
					);
				}
				$iterator->next();
			}
		}
		break;
}
	
echo json_encode($result);